package com.pingba.controller;

import com.pingba.common.Constant;
import com.pingba.entity.User;
import com.pingba.entity.oauth.WeCharUser;
import com.pingba.service.oauth.WeCharUserService;
import com.pingba.util.ReturnHelp;
import com.pingba.util.helper.JsonHelp;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * Created by Administrator on 2015/12/9 0009.
 */

@Controller
@RequestMapping(value = "/pingba/oauth", method = {RequestMethod.GET,RequestMethod.POST})
public class OauthController {
    private static Logger logger = Logger.getLogger(OauthController.class);
    @Autowired
    private WeCharUserService weCharUserService;
    /**
     * 使用微信登录
     * @param session
     * @param wecharUser
     * @return
     */
    @RequestMapping("/wechar")
    @ResponseBody
    public String wechar(HttpSession session, @RequestParam("wechar")WeCharUser wecharUser) {
        User user = weCharUserService.login(wecharUser);
        session.setAttribute(Constant.UserInSession, user);
        return ReturnHelp.getReturnString(true, user);
    }


    /**
     * 使用微信登录，如果是第一次登录会自动注册一个wechar用户，并在user表中新增一条记录
     * @param session
     * @param wecharUserJson
     * @return
     */
    @RequestMapping("/wecharJson")
    @ResponseBody
    public String wecharJson(HttpSession session, @RequestParam("wechar")String wecharUserJson) {
        logger.info("wecharUserJson: " + wecharUserJson);

        WeCharUser weCharUser = JsonHelp.objectFromJson(wecharUserJson, WeCharUser.class);
        if (weCharUser == null ) {
            return ReturnHelp.getReturnString(false, "Json Cast Error");
        }
        User user = weCharUserService.login(weCharUser);
        session.setAttribute(Constant.UserInSession, user);
        return ReturnHelp.getReturnString(true, user);
    }
}
